//
//  HiScrollContainer.swift
//  
//
//  Created by Hoa on 2021/6/15.
//

import UIKit

public protocol HiScrollContainerContentHeight {
    
    var height: CGFloat! { get set }
    
}

/// 组头 和 左右滑容器 需要实现
public protocol HiScrollContainerSectionDelegate {
    
    /// 设置下标
    func setIndex(_ index: Int)
    
    var selectedIndex: Int { set get }
}

/// 组头 和 左右滑容器 需要实现
public protocol HiScrollChildDelegate {
    
    var scrollView: UIScrollView! { get }
}

open class HiScrollContainer: UIViewController {
        
    /// 容器滑动回调
    open var containerDidScrollHandler: ((UIViewController, Int) -> Void)?
    
    var mainScrollEnabled = false
    var subScrollEnabled = false
    
    var oldScrollEnable = false
    
    var maxOffsetY: CGFloat = 150

    /// 主滑动视图
    open lazy var mainScrollView: UIScrollView = {
        let mainScrollView = UIScrollView(frame: self.view.bounds)
        mainScrollView.contentSize = CGSize.zero
        mainScrollView.delegate = self
        let pan = UIPanGestureRecognizer.init(target: self, action: #selector(panGestureRecognizerAction(recognizer:)))
        pan.delegate = self
        mainScrollView.addGestureRecognizer(pan)
        return mainScrollView
    }()
    
    /// 头部视图
    private var headerVC: (UIViewController & HiScrollContainerContentHeight)!
    
    /// 组头视图
    private var sectionVC: (UIViewController & HiScrollContainerSectionDelegate & HiScrollContainerContentHeight)!
    
    /// 子视图
    open var subContainer: HiScrollSubContainer!
    
    ///
    private var childControllers: [(UIViewController & HiScrollChildDelegate)]!
    
    public init(
        headerVC: (UIViewController & HiScrollContainerContentHeight),
        sectionVC: (UIViewController & HiScrollContainerSectionDelegate & HiScrollContainerContentHeight),
        childControllers: [(UIViewController & HiScrollChildDelegate)]) {
        super.init(nibName: nil, bundle: nil)
        
        self.headerVC = headerVC
        self.addChild(headerVC)
        headerVC.didMove(toParent: self)
        
        self.sectionVC = sectionVC
        self.addChild(sectionVC)
        sectionVC.didMove(toParent: self)
        
        self.childControllers = childControllers
        subContainer = HiScrollSubContainer(childControllers, parent: self, dataCenter: self.sectionVC)
        
        maxOffsetY = headerVC.height
        
        childControllers.forEach { vc in
            vc.scrollView?.delegate = self
            vc.scrollView.isScrollEnabled = false
        }
    }
    
    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    func setupUI() {
        
        view.addSubview(mainScrollView)
        mainScrollView.contentSize = CGSize(width: 0, height: UIScreen.main.bounds.height + headerVC.height)
        
        mainScrollView.addSubview(headerVC.view)
        headerVC.view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: headerVC.height)
        
        mainScrollView.addSubview(sectionVC.view)
        sectionVC.view.frame = CGRect(x: 0, y: headerVC.height, width: UIScreen.main.bounds.width, height: sectionVC.height)
        
        mainScrollView.addSubview(subContainer)
        subContainer.frame = CGRect(x: 0, y: headerVC.height + sectionVC.height, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - sectionVC.height)
        subContainer.delegate = self
    }
    
    /**
     * 调整HeaderVC 高度
     */
    public func adjustedHeaderVC() {
        mainScrollView.contentSize = CGSize(width: 0, height: UIScreen.main.bounds.height + headerVC.height)
        headerVC.view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: headerVC.height)
        sectionVC.view.frame = CGRect(x: 0, y: headerVC.height, width: UIScreen.main.bounds.width, height: sectionVC.height)
        subContainer.frame = CGRect(x: 0, y: headerVC.height + sectionVC.height, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - sectionVC.height)
        maxOffsetY = headerVC.height
    }
    
    var currentPanY: CGFloat = 0

    @objc func panGestureRecognizerAction(recognizer: UIPanGestureRecognizer) {
            if recognizer.state != .changed{
                currentPanY = 0
                // 每次滑动结束都清空状态
                mainScrollEnabled = false
                subScrollEnabled = false
            }else {
               let currentY = recognizer.translation(in: mainScrollView).y
               // 说明在这次滑动过程中经过了临界点
                if mainScrollEnabled || subScrollEnabled {
                    if currentPanY == 0 {
                        currentPanY = currentY  //记录下经过临界点是的 y
                    }
                    let offsetY = currentPanY - currentY //计算在临界点后的 offsetY

                    if mainScrollEnabled {
                       let supposeY = maxOffsetY + offsetY
                        if supposeY >= 0 {
                            mainScrollView.contentOffset = CGPoint(x: 0, y: supposeY)
                        }else {
                            mainScrollView.contentOffset = CGPoint.zero
                        }
                    }else {
                        childControllers[subContainer.selectedIndex].scrollView.contentOffset = CGPoint(x: 0, y: offsetY)
                    }
                }
            }
        }
}
// MARK: - UIScrollViewDelegate
extension HiScrollContainer: UIScrollViewDelegate {
    
    open func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == mainScrollView {
            if scrollView.contentOffset.y >= maxOffsetY {
                scrollView.setContentOffset(CGPoint(x: 0, y: maxOffsetY), animated: false)
//                mainScrollView.isScrollEnabled = false
//                self.childControllers[subContainer.selectedIndex].scrollView.isScrollEnabled = true
                subScrollEnabled = true
                mainScrollEnabled = false
                mainScrollView.showsVerticalScrollIndicator = false
                self.childControllers[subContainer.selectedIndex].scrollView.showsVerticalScrollIndicator = true
            }
        }else {
            if scrollView.contentOffset.y <= 0 {
                scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
//                mainScrollView.isScrollEnabled = true
//                self.childControllers[subContainer.selectedIndex].scrollView.isScrollEnabled = false
                mainScrollEnabled = true
                subScrollEnabled = false
                mainScrollView.showsVerticalScrollIndicator = true
                self.childControllers[subContainer.selectedIndex].scrollView.showsVerticalScrollIndicator = false
            }
        }
    }
    
    
    
}

extension HiScrollContainer: UIGestureRecognizerDelegate {
    
    open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        true
    }
}
extension HiScrollContainer: HiScrollSubContainerDelegate {
    
    public func pageMenuContrainer(_ pageMenuContrainer: HiScrollSubContainer, willMoveTo viewController: UIViewController, at index: Int) {
        oldScrollEnable = childControllers[pageMenuContrainer.selectedIndex].scrollView.isScrollEnabled
        scrollViewDidScroll(mainScrollView)
    }
    
    public func pageMenuContrainer(_ pageMenuContrainer: HiScrollSubContainer, didMoveTo viewController: UIViewController, at index: Int) {
        childControllers[index].scrollView.isScrollEnabled = oldScrollEnable
        scrollViewDidScroll(mainScrollView)
        containerDidScrollHandler?(viewController, index)
    }
}
